﻿using System.Text;
using Jayden.Dll.Web.HtmlControls;

namespace Jayden.Dll.Web.Controls.Google
{
	public class GoogleAnalyticsScript : Script
	{

		public string ServerTrackingId { get { return GetServerAttribute("tracking-id"); } set { SetServerAttribute("tracking-id", value); } }
		public string ServerDomain { get { return GetServerAttribute("domain"); } set { SetServerAttribute("domain", value); } }
		public bool ServerAllowLinker { get { return GetServerAttribute("allow-linker") == "true"; } set { SetServerAttribute("allow-linker", value ? "true" : null); } }

		public override void Render(System.Web.UI.HtmlTextWriter writer, Enums.RenderMode mode, int level, bool innerHtml = false) { }

		public override void ProcessJsRequest(HttpHandlerContext context)
		{
			string id = GetType().FullName;
			if (context.Js.Contains(id))
				return;
			string trackingId = ServerTrackingId;
			string domainName = ServerDomain;
			if (string.IsNullOrWhiteSpace(trackingId))
				return;
			StringBuilder builder = context.Js[id].Builder;
			builder.Append(@"
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '" + trackingId + @"']);
");
			if(!string.IsNullOrWhiteSpace(domainName))
				builder.AppendLine("_gaq.push(['_setDomainName', '" + domainName + "']);");
			if (ServerAllowLinker)
				builder.AppendLine("_gaq.push(['_setAllowLinker', true]);");
			builder.Append(@"_gaq.push(['_trackPageview']);

(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
");
		}
	}
}
